package com.jfm.jfmc.plugin.udp.collector;

import cn.hutool.core.util.StrUtil;
import com.jfm.jfmc.plugin.udp.enums.ResultValue;
import com.jfm.jfmc.plugin.udp.utils.UDPUtil;
import com.jfm.jfmm.collector.driver.ACollectorDriver;
import com.jfm.jfmm.collector.driver.UDPDriver;
import com.jfm.jfmm.collector.entity.collect.CheckResult;
import com.jfm.jfmm.collector.entity.collect.CollectResult;
import com.jfm.jfmm.collector.entity.collect.Param;
import com.jfm.jfmm.collector.entity.collect.param.UDPParam;
import com.jfm.jfmm.collector.entity.collect.result.UDPResult;
import com.jfm.jfmm.collector.enums.ResultType;
import jakarta.annotation.PostConstruct;

/**
 * @author DYang
 * @since 2024-10-11 22:57
 */
public class UDPCollect extends UDPDriver {

    @PostConstruct
    @Override
    public void register() {
        ACollectorDriver.collectorMap.put(this.supportProtocol(), this);
    }

    @Override
    public CheckResult perCheck(Param reqParam) {
        UDPParam param = this.transformParam(reqParam);

        if (param == null) return new CheckResult(ResultType.EMPTY_PARAM, "param is null");

        if (StrUtil.isEmpty(param.getHost())) return new CheckResult(ResultType.EMPTY_PARAM, "host is empty");

        if (param.getPort() == null) return new CheckResult(ResultType.EMPTY_PARAM, "port is empty");

        return new CheckResult(ResultType.SUCCESS);
    }

    @Override
    public CollectResult collect(Param reqParam) {
        long startTime = System.currentTimeMillis();
        UDPParam param = this.transformParam(reqParam);

        int timeout = param.getTimeout() == null ? 5000 : param.getTimeout();
        boolean available = UDPUtil.isAvailable(param.getHost(), param.getPort(), timeout, param.getContent());
        long responseTime = System.currentTimeMillis() - startTime;

        UDPResult result = UDPResult.build()
                .result(available ? ResultValue.SUCCESS.getValue() : ResultValue.FAIL.getValue())
                .delay(responseTime)
                .host(param.getHost())
                .port(param.getPort());

        CollectResult collectResult = new CollectResult();
        return collectResult
                .protocol(supportProtocol())
                .result(result)
                .startTime(startTime)
                .responseTime(responseTime);

    }

}
